package com.aliyun.messagemgt.application.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.messagemgt.application.service.SmsMonitorService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.UUID;

/**
 * @author byp
 * @date 2020/7/23
 */
@Service
public class SmsMonitorServiceImpl implements SmsMonitorService {

    //@Value("${ali.dysms.accessKeyId}")
    private String accessKeyId;
    //@Value("${ali.dysms.accessKeySecret}")
    private String accessKeySecret;
    //@Value("${ali.dysms.domain}")
    private String domain;
    //@Value("${ali.dysms.signName}")
    private String signName;
    //@Value("${ali.dysms.templateCode}")
    private String templateCode;
    //@Value("${ali.dysms.version}")
    private String version;
    //@Value("${ali.dysms.regionId}")
    private String regionId;
    //@Value("${ali.dysms.product}")
    private String product;

    private static Logger logger = LoggerFactory.getLogger(SmsMonitorServiceImpl.class);

    @Override
    public void executeMonitor(String phones, String msgParams) throws ClientException {
        logger.info("告警通知人员手机号：{}", phones);
        String apiAction = "SendSms";
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(regionId, regionId, product, domain);
        IAcsClient client = new DefaultAcsClient(profile);


        String msg = "尊敬的用户，您在三河市统一通知中心设置的短信配额包当前剩余量小于{0}条，请及时调整短信配额量，以免影响正常使用。";
        Object[] param = msgParams.split(",");
        String formatMsg = MessageFormat.format(msg, param);
        logger.info("配额告警短信信息：{}", formatMsg);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(phones);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        //参考：request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")
        JSONObject params = new JSONObject();
        params.put("content", formatMsg);
        request.setTemplateParam(params.toString());
        //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        request.setOutId(UUID.randomUUID().toString());
        try {
            logger.info("配额告警短信IAcsClient：{}", JSONObject.toJSONString(client));
            logger.info("配额告警短信request：{}", JSONObject.toJSONString(request));
            SendSmsResponse response = client.getAcsResponse(request);
            if (response.getCode() != null && "OK".equals(response.getCode())) {
                logger.info("告警发送成功！");
            } else {
                logger.info("告警发送失败！msg：{}", JSONObject.toJSONString(response));
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
